# -*- coding: utf-8 -*-
import serial,sys,time,json,redis,binascii,math,traceback
flog=open("data.log",'a+')
portType=0

try:
    rd = redis.Redis(host='127.0.0.1',port=6379)
    conffile = open('config.json','r')
    # conffile = open('/home/wwwroot/pavgps/config.json','r')
    confstr = conffile.read()
    conf = json.loads(confstr)
    conf['windlassDiam']  = int(conf['windlassDiam'])
    conf['pulleyDiam']  = int(conf['pulleyDiam'])
    conf['cycles']  = int(conf['cycles'])
    conf['lineDiam']  = int(conf['lineDiam'])
    conf['initDiam']  = int(conf['initDiam'])
    ser = serial.Serial(conf["EncoderSerialPort"], 9600, timeout=0.5)
    # if 'TempPortType'  in conf:
    #     portType = conf["TempPortType"]


except Exception as e:
    print("============")
    errstr=traceback.print_exc()
    # flog.write(""+repr(e));
    # flog.close()
    quit()

def getTemp(ser):
    temp = 0
    try:
        if ser!=None:
            cmd = bytes.fromhex("01 03 00 00 00 02 C4 0B")
            ser.write(cmd)
            n=ser.inWaiting()                             #串口接收
            if n:
                data= str(binascii.b2a_hex(ser.read(n)))[2:-1]          #Hex转换成字符串
                hasstr =data.find('0103')
                if hasstr>-1:
                    circle =data[6:10]
                    temp = round(int(circle,16)/1024,2)
                    circle2 =data[10:14]
                    temp2 = int(circle2,16)
                    temp=temp+temp2-512.5
                    return round(temp,3)
    except:
        print("ERR")
        temp =  0
    return temp

data_arr=[] #最近的数值
last_num = 0 #上次读表数值

def getMeter(EncoderCycles, windlassDiam,  pulleyDiam, cycles, lineDiam, initDiam ):
    proportion = pulleyDiam / windlassDiam  #卷扬机滑轮比例
    windlassCycles = EncoderCycles * proportion #卷扬机圈数

    ######################
    allLayer = math.ceil(windlassCycles / cycles) #总共达到的层级
    curLayer = 0
    high = 0

    if windlassCycles<0:
        high=(initDiam + lineDiam*curLayer)*math.pi*windlassCycles
        return high

    if windlassCycles>=cycles:
        for i in range(allLayer):
            curLayer = i+1
            high =  high + (initDiam + lineDiam*curLayer)*math.pi*cycles

    mod = windlassCycles % cycles
    curLayer=curLayer+1;
    # print(EncoderCycles,'Q')
    # print(mod,' M')

    if mod !=0:
        high =high+(initDiam + lineDiam*curLayer)*math.pi*mod;

    return high

lastHigh=0;
up = 0;
while(1):
    tmp=-999
    tmp = getTemp(ser)
    print(tmp)
    if conf['encoderDrct'] == '2':
        if tmp>0:
            tmp = 0-tmp
        else:
            tmp = abs(tmp)

    flog.write("\r\n"+ str(tmp))
    data_arr.append(tmp)
    # print(data_arr[-1])

    if tmp>-999:
        rd.set("encoder_circle",tmp,30)
        high = getMeter(tmp, conf['windlassDiam'], conf['pulleyDiam'], conf['cycles'], conf['lineDiam'], conf['initDiam'])
        rd.set("high",round(high,2),60*60)

        if high > lastHigh+5:
            up =1

        if lastHigh>50:
            # print(high-lastHigh,' ----')
            if high-lastHigh<-8 and up == 1:
                print(lastHigh ,' down')
                rd.rpush("down",1)
                up = -1
        lastHigh = high
        print("h:" , high)

    time.sleep(0.2)
